package com.ruoyi.common.utils.sms;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.ruoyi.common.config.SMSConfig;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 描述 短信发送工具类
 * 作者 ZhangPing
 * 创建时间 2023/9/25 15:20
 */
@Slf4j
@NoArgsConstructor
@Component
public class SMSUtil {

    @Autowired
    private SMSConfig smsConfig;

    public boolean sendSMS(String phoneNumber, String code) {
        try {
            log.info("开始发送短信，手机号码：" + phoneNumber + "，验证码：" + code);
            String[] params = {code};
            SmsSingleSender sender = new SmsSingleSender(smsConfig.getAppId(), smsConfig.getAppKey());
            SmsSingleSenderResult result = sender.sendWithParam("86", phoneNumber, smsConfig.getTemplateId(), params, smsConfig.getSmsSign(), "", "");
            boolean success = result.result == 0;
            if (success) {
                log.info("短信发送成功");
            }else {
                log.info("短信发送失败");
            }
            return success;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 生成验证码
     *
     * @return
     */
    public String getCode() {
        String str = "0123456789";
        StringBuilder uuid = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            uuid.append(ch);
        }
        return uuid.toString();
    }
}
